package com.devops.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devops.admin.mapper.DOSEnvMapper;
import com.devops.admin.model.*;
import com.devops.admin.po.DOSEnvPo;
import com.devops.admin.service.*;
import com.devops.admin.util.Assert;
import com.devops.admin.vo.DOSPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassNem DOSEnvServiceImpl
 * @Description TODO
 * @Author heyabo
 * @Date 2022/3/18 17:17
 * @Version 1.0
 **/
@Service
public class DOSEnvServiceImpl extends ServiceImpl<DOSEnvMapper, DOSEnv> implements DOSEnvService {

    @Autowired
    private DOSProjectService dosProjectService;
    @Autowired
    private DOSHelmChartRepositoryService dosHelmChartRepositoryService;
    @Autowired
    private DOSEnvClusterRelationService dosEnvClusterRelationService;
    @Autowired
    private DOSClusterService dosClusterService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteEnv(Integer envId) {

        LambdaQueryWrapper<DOSProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DOSProject::getEnvId,envId);
        List<DOSProject> dosProjects = dosProjectService.list(queryWrapper);
        //判断项目是否已经绑定
        Assert.isTrue(CollectionUtil.isEmpty(dosProjects),"环境已经绑定项目无法删除");
        LambdaQueryWrapper<DOSEnvClusterRelation> envQueryWrapper = new LambdaQueryWrapper<>();
        envQueryWrapper.eq(DOSEnvClusterRelation::getEnvType,envId);
        long count = dosEnvClusterRelationService.count(envQueryWrapper);
        Assert.isTrue(count < 1,"环境已经绑定了集群无法删除");
        return this.removeById(envId);
    }

    @Override
    public TableResult<DOSEnvPo> getEnvByName(DOSEnv env,DOSPageVo pageVo) {
        Page<DOSEnv> page = new Page<>(pageVo.getPageNum(),pageVo.getPageSize());
        TableResult<DOSEnvPo> tableResult = new TableResult<>();
        List<DOSEnvPo> dosEnvs = new ArrayList<>();
        List<DOSEnvPo> dosEnvPos = baseMapper.selectPages(page,env);
        setRepository(dosEnvs, dosEnvPos);
        Pagination p = Pagination.builder().pageNum(page.getCurrent()).pageSize(page.getSize()).total(page.getTotal()).build();
        tableResult.setList(dosEnvs);
        tableResult.setPagination(p);
        return tableResult;
    }

    @Override
    public TableResult<DOSEnvPo> getListPage(DOSModel modelPage, DOSPageVo pageVo) {
        Page<DOSEnv> page = new Page<>(pageVo.getPageNum(),pageVo.getPageSize());
        List<DOSEnvPo> dosEnvs = new ArrayList<>();
        TableResult<DOSEnvPo> tableResult = new TableResult<>();
        List<DOSEnvPo> dosEnvPos = baseMapper.selectPages(page,new DOSEnv());
        setRepository(dosEnvs, dosEnvPos);
        Pagination p = Pagination.builder().pageNum(page.getCurrent()).pageSize(page.getSize()).total(page.getTotal()).build();
        tableResult.setList(dosEnvs);
        tableResult.setPagination(p);
        return tableResult;
    }

    @Override
    public List<DOSEnv> getAllList() {
        return this.list();
    }


    /**
     * @Author heyabo
     * @Description 设置环境关联的仓库
     * @Date 09:07 2022/3/29
     * @Param [dosEnvs, envPage]
     * @return void
     **/
    private void setRepository(List<DOSEnvPo> dosEnvs, List<DOSEnvPo> dosEnvPos) {
        if (CollectionUtil.isNotEmpty(dosEnvPos)){
            List<Integer> envIds = dosEnvPos.stream().map(DOSEnv::getId).collect(Collectors.toList());
            LambdaQueryWrapper<DOSHelmChartRepository> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.in(DOSHelmChartRepository::getEnvId,envIds);
            List<DOSHelmChartRepository> repositories = dosHelmChartRepositoryService.list(queryWrapper1);
            Map<Integer, List<DOSHelmChartRepository>> map = repositories.stream().collect(Collectors.groupingBy(DOSHelmChartRepository::getEnvId));
            dosEnvPos.forEach(env->{
                DOSEnvPo po = new DOSEnvPo();
                BeanUtil.copyProperties(env,po);
                po.setRepositories(map.get(env.getId()));
                dosEnvs.add(po);
            });
        }
    }
}
